Introduction to Quarto

Introduction

In this tutorial you will learn about another way you can use RStudio to interact with R, using Quarto (the document you are reading right now was produced using Quarto). You will also learn about RStudio projects and about the standard directory structure that you will use for all RStudio projects in the watershed course.

RStudio Projects

RStudio uses projects to organize code and files that are related to each other. You could use an RStudio project to organize all of your code and data for a research project. You might use a project for all of the code you write in a particular course. You will probably want to use different RStudio projects to organize your work for different parts of the watershed course.

You should create a directory (folder) to hold your RStudio projects. I recommend creating a directory named Projects or RProjects on your computer. Put it in either your home folder or your Documents folder. You can create your Projects directory how you would normally create a directory on your computer or you can do it using RStudio.

To create a Projects directory using RStudio, open RStudio then select the Files tab in the lower right pane (see figure below). Navigate to the directory that you want to create your Projects directory in using the tools in the Files tab. You can move up a directory (to the one that contains the one you are currently in) by clicking on the up arrow (see 1 in the figure). You can also move up through directories by clicking on folders in the bar above it (see 2 in the figure). You can move into a directory listed in the Files tab by clicking on the name of the directory (see 3 in the figure). Find your way to the appropriate directory (either your Home directory or your Documents directory).

Create your Projects directory by clicking the New Folder button (see 4 in the figure). Enter the name of your new directory, Projects. It should now appear in your Files tab (see 3 in figure). If it does not, then click the Refresh button, indicated by a circular arrow (see 5 in figure). Your Projects directory should now appear.

The Files tab in RStudio.

Enter your Projects directory by clicking on its name in the Files tab. It should be empty. Now you are ready to create a new RStudio project.

From the RStudio File menu (not the Files tab), select New Project…. A window similar to the following one should appear.

Creating a new project in RStudio.

Select the New Directory option. A New Project Wizard window similar to the following figure should appear. Select the option Quarto Project.

Creating a new project in RStudio–second screen.

The New Project Wizard window should now like the one in the following figure. Enter watershed_R_Intro for the directory name, and use the Browse button to navigate to the Projects directory you created earlier. This will ensure that the new project will be located in your Projects directory. Click on Create Project to create your project.

Creating a new project in RStudio–third screen.

A new RStudio project is simply a directory (in this case called watershed_R_Intro) that contains a project file (in this case watershed_R_Intro.Rproj), a .qmd file (watershed_R_Intro.qmd), and a .yml file (*_quarto.yml). RStudio will create all three of these and open the project. You can see that you are working in the watershed_R_Intro* project, because the bar at the top of the RStudio window now says the name of the project. RStudio has also taken you into the watershed_R_Intro project directory in the Files tab in the lower right pane. Within the directory, you should see the project file.

An open project.

Project settings

The *_quarto.yml* contains settings for the project. We will edit this file to indicate that the project directory should act as the working directory when we execute code. Click on the name of the *_quarto.yml* file in the Files pane to open the file. Add the following line to the file execute-dir: project. The text should be indented as in the following figure.

Save the file by hitting the button with the disk icon. Then close the file by clicking the x on the tab after the file name.

Editing project settings.

Project organization

We will organize all of our R projects in a similar way in the watershed class. We will create different sub-directories for different types of files. We will use the following sub-directories:

sub-directory types of files contained in sub-directory
code R code, including Quarto code that we write
raw_data Any data that we import into the project from elsewhere, including other R projects we have created
clean_data Any data products we create in the current project
outputs Plots and other things we might want to include in a paper, presentation, or homework submission

Use the + Folder button in the Files tab to create each of these directories within your watershed_R_Intro project directory. You should see the subdirectories appear as you add each one (you may need to click the refresh button).

Standard subdirectories we will create for each project.

Quarto

Now that we have our project set up, let’s put something it it! We will produce Quarto documents throughout the course. Quarto documents integrate R commands, output from R commands, and text that you write to explain your project, what you are doing, and what the results are. This is a great way to share your work with others or to keep a record of your thought process and your explorations in R so that you can refer to them later. I often develop code in Quarto, even if I plan to create a more compact version later to run on a server.

Quarto documents can be ‘rendered’ to produce a document that can be opened by a web browser (am html file like the one you are reading), a Microsoft Word document, or a PDF file. Often you will start by rendering html files as you work on your code, because they take the least amount of time to render. Then if you want a PDF file to distribute later or a Word Document to do some additional formatting with, then you can render one of those when you are done developing your code.

Limited text formatting in Quarto documents is achieved using the markup language Markdown (specifically, R Markdown). You can use Markdown to do things like make headings and subheadings in your document, italicize text, create tables, link to external web pages, etc. All of the formatting that you see in this document was done using Markdown.

In this tutorial, we will discuss some of the ways you can format text using Markdown. However, it is useful to keep a cheat sheet handy like this one from Posit.

Creating your first Quarto document

Creating a new Quarto document is easy. From within your project, select New File then Quarto Document from the File menu (not the Files tab). A window should open similar to the one in the following figure.

Give your document the title Basic Plotting (Note that this is not the file name. It is the title that will appear at the top of your document.) Make sure you put your name in the author field. Make sure Document is selected in the pane on the left and that HTML is selected as the default output format (all of these things are easy to change later). Once everything is set up correctly, click Create to create your document.

Setting up a new Quarto document.

RStudio will open your new Quarto document in the pane on the top left of the RStudio window. The result should look similar to the following figure.

Your new Quarto document.

Although you have created the new Quarto document file you have not saved it yet. Let’s do that before we do anything else so that we do not lose our work. From the File menu, select Save. A save window should pop up. Navigate to the code subdirectory you created earlier (this is code). Save your file with the name basicPlotting.qmd.

If you have done everything correctly, you should be able to open the code directory in the Files tab and see your basicPlotting.qmd file listed there (if not try the refresh button). You should also see the name basicPlotting.qmd listed on the tab at the top of your document (in the top left pane). Everything should look similar to the following figure (though your panes may be organized a bit differently).

How things should appear after you have saved your Quarto file.

Telling R how to handle errors while rendering and to create standalone html files

By default, when R renders a Quarto document that contains R code with an error, the rendering process will fail and a rendered file (e.g., html) will not be created. Instead, we will set up our Quarto documents so that the file is rendered, but error messages are printed within the rendered document.

The default html rendering behavior is to produce an html document with several supporting files. Instead we will set up our Quarto documents so that R will render them as standalon html files (that do not need additional supporting files). This will make it easier to share and turn in your code.

Make these two changes to all of your Quarto documents in the watershed course.

To change the default error handling behavior add the following lines to the setup section at the top of the document.

execute:
  error: true

To setup standalone html file rendering replace the format: html line in the setup section with the following three lines

format: 
  html:
    embed-resources: true

The results should look like the following figure.

How things should appear after you have modified your document to change the error handling behavior and the html rendering settings.

Before you do anything else, save your file. Finally we are all set up! Don’t worry, you will go through these steps again and again and they will eventually become familiar.

Quarto document template

Now that our Quarto document has been created and set up we are ready to start looking at it. When we had RStudio create the document it gave the document the title and author. This information and the setup information we modified is listed at the top of the document.

Following that block is the body of the document. This includes Markdown-formatted text and R code blocks. RStudio will always create a Quarto document with this basic template. It is useful, because it starts us out with examples of some of the things we will want to do in Quarto documents. Let’s look at some of the code.

Let’s render the document to see what the output looks like! Click the Render button (with the blue arrow on it) at the top of your Quarto document. RStudio may ask you to install some packages the first time you do this. Allow it to install the packages. Once the rendering is finished a browser tab shopuld pop up with the output. It should look something like the following figure.

The rendered document.

Let’s compare the Quarto code to the rendered output.

First note that R created a title and listed the author using the information we specified earlier (that appears in the setup section at the beginning of the Quarto document).

The first line of code in the body of the Quarto document is

## Quarto

This creates the heading with the text Quarto in the knitted output. This is followed by some text that includes a link. Then there is another heading and some more text. You can match the code with the corresponding output in the rendered html document in your browser tab.

The next part of the code is a bit more interesting. It is an R code block.

```{r}
1 + 1
```

A block starting with ```{r} and ending with ``` will be interpreted as including R commands that will be executed when the document is rendered. The code within the block 1 + 1 tells R to run compute the sum.

If we compare this code block to the knitted output, we see that the code 1 + 1 is printed followed by the result (2). It is important to emphasize that the R code is written in the Quarto document, then the code is run and the commands and results are printed in the output document when the document is rendered.

The next part of the Quarto code produces some more text. Then there is another code block,

```{r}
#| echo: false
2 * 2
```

When the document is rendered, the output from this block will be shown (4), but the code itself will not be printed due to the inclusion of #| echo: false at the top of the block.

The document concludes with some more text.

Writing our own code

The Quarto document that RStudio generated for us is just there to give us an example that we can build on. We really want to write our own text and code and produce our own output. We will delete the code that RStudio added, and we will replace it with our own. Start by deleting everything below the setup section at the top of the document. Your document should look like the following figure.

After the example code has been deleted.

We will write some code to generate a plot of the curve \(y=x^2\) like we did in the first tutorial. However, this time your code will be saved in the Quarto document, and you will produce an output file that shows the results of your work. Before we write any R code, we should explain what we are doing by writing some text. Let’s start with a heading and then write an explanation. The code that I wrote is shown in the following figure.

Adding a new heading and some explanatory text.

One thing you may notice in the Quarto document is the code $y=x^2$ that shows up in the heading and in the text. This produces a nicely formatted equation using \(\LaTeX\) code. \(\LaTeX\) is a mathematical typesetting language. We will not use it much in the watershed class, but if you are interested in learning more about it it is easy to find tutorials by searching online (or talk to Yurk).

Next we will add an R code block. We will construct the two vectors and build the plot in the same block. The commands should look familiar, since they are the same as in the first tutorial.

Adding a code block to create the vectors and make the plot. Save your Quarto document and knit it! How does it look?

Practicing with Quarto

Now we will practice formatting text in a Quarto document. Create a new Quarto document within your watershed_R_Intro project. Give it the title Practicing Formatting with Quarto. Don’t forget to make the appropriate changes to the setup section like we did in the last Quarto document. Delete all of the code after the setup section (also like we did last time), and save your file in the code directory. Give it the name practicingQuartoFormatting.qmd.

If you have done everything correctly your RStudio window should look similar to the following figure.

A new Quarto file for practicing formatting text..

Add some text to your document to explain what you are doing (learning about formatting text in Quarto documents).

You can create different levels of headings in Quarto documents using different numbers of # symbols. If you use ## for headings, then you can use ### for subheadings, #### for sub-subheadings, and so on. At each level the font size of the heading gets smaller.

The following includes my code to introduce my document and to explore headings and subheadings.

Different levels of headings. Next create a heading for a section titled Basic text formatting.

You can italicize text by including it between asterisks. For example, writing *this is in italics* in your document will produce the same text but printed in italics in your output. Text can be written in a bold font by surrounding text in pairs of asterisks. For example, writing **this is in bold** will produce bold text in the output. Write some italicized text and some bold text in your Basic text formatting section.

Writing italicized and bold text in a Quarto document.

Next create a section titled Enumerated and bulleted lists in your document. Enumerated lists are easy to create in Quarto documents. The code

1. Item number 1
2. Item number 2
3. Item number 3

will produce the output

  1. Item number 1
  2. Item number 2
  3. Item number 3

And the code

- First item
- Second item
- Third item

will produce the output

  • First item
  • Second item
  • Third item

Add an enumerated list and a bulleted list to your Quarto document.

Finally, add a section called Tables to your document.

The following code

Column 1 Title  |  Column 2 Title
----------------|----------------
1              | stuff
2              | more stuff
3              | even more stuff

produces the table

Column 1 Title Column 2 Title
1 stuff
2 more stuff
3 even more stuff

Add a table to your document.

Now save and render your document. Inspect your output and compare it to your Quarto code. Does it look like you expected it to look?